<template>
  <div style="margin-top: 20px;">
    <h3>饼状图</h3>
    <BasicForm @register="register" @submit="handleSubmit" />
    <div ref="chartRef" :style="{ height, width }"></div>
  </div>
</template>

<script lang="ts" setup>
  import { PropType, ref, Ref } from 'vue';
  import { BasicForm, useForm, FormSchema } from '@/components/Form';
  import { useECharts } from '@/hooks/web/useECharts';

  const props = defineProps({
    width: {
      type: String as PropType<string>,
      default: '100%',
    },
    height: {
      type: String as PropType<string>,
      default: 'calc(100vh - 78px)',
    },
    queryResult: [],
    keyOptions: [],
  });

  const formSchema: FormSchema[] = [
    {
      field: 'categoryKey',
      label: '分类字段',
      component: 'Select',
      required: true,
      componentProps: {
        options: props.keyOptions,
      },
    },
    {
      field: 'valueKey',
      label: '统计字段',
      component: 'Select',
      required: true,
      componentProps: {
        options: props.keyOptions,
      },
    },
  ];

  const [register] = useForm({
    baseColProps: { span: 10 },
    labelWidth: 80,
    showActionButtonGroup: true,
    schemas: formSchema,
  });

  const chartRef = ref<HTMLDivElement | null>(null);
  const { setOptions } = useECharts(chartRef as Ref<HTMLDivElement>);
  
  function handleSubmit(values) {
    let dataMap = new Map();
    for (const item of props.queryResult) {
      let k = item[values.categoryKey];
      let v = item[values.valueKey];
      if (dataMap.has(k)) {
        dataMap.set(k, dataMap.get(k) + v);
      } else {
        dataMap.set(k, v);
      }
    }
    const data = Array.from(dataMap).map(([key, value]) => ({ name: key, value: value }));
    setOptions({
      tooltip: {
        trigger: 'item'
      },
      series: [
        {
          type: 'pie',
          radius: '50%',
          center: ['50%', '50%'],
          data: data,
          labelLine: { show: false },
          label: {
            show: true,
            formatter: '{b} \n ({d}%)',
          },
        },
      ],
    });
  };
</script>